package com.example.fruitsale.controller;


import com.example.fruitsale.common.ApiResponse;
import com.example.fruitsale.entity.Order;
import com.example.fruitsale.entity.UserManage;
import com.example.fruitsale.entity.WXSessionModel;
import com.example.fruitsale.entity.WxLogin;
import com.example.fruitsale.service.UserService;
import com.example.fruitsale.utils.HttpClientUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import static com.example.fruitsale.utils.JSONUtils.parseJSON2Map;
import static com.example.fruitsale.utils.JSONUtils2.objectToJsonStr;
import com.example.fruitsale.utils.*;

@Api(tags = "WechatController", description = "微信登录管理")   //tags是api名字，description是简介，value:已废用
@RestController
@RequestMapping("/wechat")
public class WechatController {
    @Autowired
    UserService userService;

    @ApiOperation(value = "微信登录")
    @PostMapping("/wxLogin")
    public ApiResponse<Map<String, Object>> wxLogin(@RequestBody WxLogin requestData) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, Object> result = new HashMap<>();//返回结果
        //小程序端通过 wx.login() 获取临时登录凭证code，传到后端，配合appid和secret可以调用 auth.code2Session 接口，换取用户唯一标识 openid 和 会话密钥 session_key。
        Map<String, String> param = new HashMap<>();
        String appid ="wx5b87b8198acaa2a4" ;
        String secret = "7d8ca16c7bcd394d052b7cba740db9c7";
        param.put("appid", appid);
        param.put("secret", secret);
        param.put("js_code", requestData.getCode());
        param.put("grant_type", "authorization_code");
        // 调用微信服务器后得到的返回结果,json格式，如{"session_key":"vHbUrlGBVJuJX17SPZIjsQ==","openid":"obOn74vfI9wyIbN_HrMtRrUZmpaU"}
        String wxResultJson = HttpClientUtil.doGet(url, param);
        //使用工具类jsonutils的parseJSON2Map将json字符串转换成map
        System.out.println("wxresult="+wxResultJson);
        Map<String, Object> wxResultMap = parseJSON2Map(wxResultJson);
        //如果解析出来发现验证码已用过或者不匹配，则返回错误
        if(wxResultJson.contains("errcode")){
//            result.put("errcode",wxResultMap.get("errcode"));
//            result.put("errmsg",wxResultMap.get("errmasg"));
            return ApiResponse.<Map<String, Object>>builder().code(400).message("失败").data(wxResultMap).build();
        }
        //成功的话保存下sessionkey和openid
        String openid = openid=wxResultMap.get("openid").toString();
        String session_key = wxResultMap.get("session_key").toString();
        System.out.println("jsonStr转map,sessionkey=" +wxResultMap.get("session_key") +",openid="+wxResultMap.get("openid"));

        // 根据返回的User实体类，判断用户是否是新用户，是的话，将用户信息存到数据库；不是的话，更新最新登录时间
        //        obOn74vfI9wyIbN_HrMtRrUZmpaU
        UserManage userEntity = userService.getByOpenid(wxResultMap.get("openid").toString());
        // uuid生成唯一key，用于维护微信小程序用户与服务端的会话
        String skey = UUID.randomUUID().toString();
        System.out.println("userEntity = "+userEntity);

        int userId;
        if(userEntity == null){
            userEntity = new UserManage();
            userEntity.setOpenid(openid);
            userEntity.setSkey(skey);
            userEntity.setHeadImage(requestData.getAvatarUrl());
            System.out.println(requestData.getAvatarUrl());
            userEntity.setNickname(requestData.getNickName());
            userEntity.setGender(requestData.getGender());
            userEntity.setGmtCreate(new Date());
            userEntity.setLastVisitTime(new Date());
            userEntity.setSessionKey(session_key);
            int flag = userService.addUser(userEntity);
            if(flag ==1){
                System.out.println("新用户，登录注册成功");
            }
            else{
                System.out.println("新用户，登录失败");
            }
        }
        else{
            // 已存在，更新用户登录时间
            userEntity.setLastVisitTime(new Date());
            userEntity.setSessionKey(session_key);
            // 重新设置会话skey
            userEntity.setSkey(skey);
            userId = userEntity.getUserId();
            Boolean flag = userService.updateById(userEntity.getUserId(),userEntity);
            if(flag ==true){
                System.out.println("老用户，登录注册成功");
            }
            else{
                System.out.println("老用户，登录失败");
            }
        }

        userId = userService.getUseridByOpenid(openid);
        result.put("skey",skey);
        result.put("userId",userId);
        return ApiResponse.<Map<String, Object>>builder().code(200).message("成功").data(result).build();
    }


    @ApiOperation(value = "检查登录状态是否过期", notes = "")  //value是Get /Msg/list旁边的那个api简介；notes是点开的介绍，可用于详细说明api作用
    @GetMapping("/checkLoginState")
    public ApiResponse<Map<String, Object>> checkLoginState( @ApiParam(value="用户id，作为验证",required = true) @RequestParam(value="userId",required=true) Integer userId,
                                                     @ApiParam(value="skey",required = true) @RequestParam(value="skey",required=true) String skey){
        Map<String, Object> result = new HashMap<>();//返回结果
        UserManage userEntity = userService.getUserBySkey(skey);
        if(userEntity==null || userEntity.getUserId().equals(userId)==false){
            return ApiResponse.<Map<String, Object>>builder().code(400).message("用户表中不存在该用户").data(result).build();
        }
        //a早于b返回true，否则返回false
        if(userEntity.getLastVisitTime().getTime()-new Date().getTime()>7*24*60*60*1000){
            return ApiResponse.<Map<String, Object>>builder().code(400).message("skey过期了，需重新登录").data(result).build();
        }

        // 更新skey
        skey = UUID.randomUUID().toString();
        userEntity.setSkey(skey);
        userEntity.setLastVisitTime(new Date());
        Boolean flag = userService.updateById(userEntity.getUserId(),userEntity);
        if(flag ==true){
            System.out.println("更新skey成功");
        }
        else{
            System.out.println("更新失败");
        }
        result.put("skey",skey);
        result.put("userId",userId);
        return ApiResponse.<Map<String, Object>>builder().code(200).message("登录状态未失效").data(result).build();
    }


}
